/*
 *  Copyright (C) 2025 ameise <ameise.wang@gmail.com> - All Rights Reserved
 *
 *  This file is part of e3net.
 *
 *  e3net is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  e3net is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with e3net. If not, see <https://www.gnu.org/licenses/>.
 */

package e3net

import (
	"net"
	"os"
)

func GetInternalIP() string {
	_gInnerOnce.Do(func() {
		var err error
		_gInnerIp, _ = getInternalIP()
		if err != nil {
			panic(err)
		}
	})
	return _gInnerIp
}

func GetExternalIP() string {
	_gExternalOnce.Do(func() {
		var err error
		_gExternalIp, err = getExternalIp()
		if err != nil {
			_gExternalIp = GetInternalIP()
		}
	})
	return _gExternalIp
}

func GetHostName() string {
	_gHostNameOnce.Do(func() {
		var err error
		_gHostName, err = os.Hostname()
		if err != nil {
			_gHostName = GetExternalIP()
		}
	})
	return _gHostName
}

func SplitHostPort(addr string) (string, string, error) {
	return net.SplitHostPort(addr)
}

func GetHost(addr string) (string, error) {
	a, _, err := net.SplitHostPort(addr)
	return a, err
}

func GetPort(addr string) (string, error) {
	_, p, err := net.SplitHostPort(addr)
	if err != nil {
		return "0", err
	}
	return p, nil
}
